package com.atguigu.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration //配置类
//@EnableWebSecurity //开启SpringSecurity的自定义配置（在SpringBoot项目中可以省略此注解）
@EnableMethodSecurity //开启基于方法的授权
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        //开启授权保护
        http.authorizeRequests(
                authorize -> authorize
                        // .requestMatchers("/user/list").hasAuthority("USER_LIST")
                        // .requestMatchers("user/add").hasAuthority("USER_ADD")
                        // .requestMatchers("/user/**").hasRole("ADMIN")
                        //对所有请求开启授权保护
                        .anyRequest()
                        //已认证的请求会被自动授权
                        .authenticated()
        ).formLogin(form -> {
            form.loginPage("/login") //使用自定义页面
                    .permitAll() //无需授权即可访问页面
                    .successHandler(new MyAuthenticationSuccessHandler()) //认证成功时的处理
                    .failureHandler(new MyAuthenticationFailureHandler()) //认证失败时的处理
            ;
            // .formLogin(withDefaults()); //使用表单授权方式
            // .httpBasic(withDefaults()); //使用基础授权方式
        }).logout(
                logout -> {
                    logout.logoutSuccessHandler(new MyLogoutSuccessHandler()); //注销成功时的处理
                }
        ).exceptionHandling(
                exception -> {
                    exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()); //请求未认证的处理（指的是没有登录不能登录的页面）
                    exception.accessDeniedHandler(new MyAccessDeniedHandler());
                }
        ).cors(
                withDefaults() //开启全局跨域
        ).sessionManagement(
                session -> {
                    session.maximumSessions(1).expiredSessionStrategy(new MySessionInformationExpiredStrategy());
                }
        );

        //关闭csrf攻击防御
        http.csrf(csrf -> csrf.disable());

        return http.build();
    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        //创建基于内存的用户信息管理器
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        //使用manager管理UserDetails对象
//        manager.createUser(
//                ////创建UserDetails对象，用于管理用户名、用户密码、用户角色、用户权限等内容
//                User.withDefaultPasswordEncoder().username("Zyniin").password("password").roles("USER").build()
//        );
//        return manager;
//    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        //创建基于数据库的用户信息管理器
//        return new DBUserDetailsManager();
//    }
}
